package com.example.cemenghuii.service;

import com.example.cemenghuii.entity.Course;
import com.example.cemenghuii.mapper.CourseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CourseService {

    @Autowired
    private CourseMapper courseMapper;

    /**
     * 根据ID查询课程
     */
    public Course getCourseById(Long id) {
        return courseMapper.selectById(id);
    }

    /**
     * 创建课程
     */
    public boolean createCourse(Course course) {
        course.setCreateTime(LocalDateTime.now());
        course.setUpdateTime(LocalDateTime.now());
        course.setViewCount(0);

        // 企业用户发布的课程需要审核
        if (course.getPublisherId() != null) {
            course.setStatus(0); // 待审核
        } else {
            course.setStatus(1); // 管理员发布直接通过
        }

        return courseMapper.insert(course) > 0;
    }

    /**
     * 更新课程
     */
    public boolean updateCourse(Course course) {
        course.setUpdateTime(LocalDateTime.now());
        return courseMapper.update(course) > 0;
    }

    /**
     * 删除课程
     */
    public boolean deleteCourse(Long id) {
        return courseMapper.deleteById(id) > 0;
    }

    /**
     * 分页查询课程列表
     */
    public Map<String, Object> getCourseList(String courseName, String author, Integer status,
                                             Long publisherId, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<Course> courseList = courseMapper.selectCourseList(courseName, author, status, publisherId, offset, pageSize);
        int total = courseMapper.countCourses(courseName, author, status, publisherId);

        Map<String, Object> result = new HashMap<>();
        result.put("list", courseList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 审核课程
     */
    public boolean auditCourse(Long id, Integer status) {
        Course course = courseMapper.selectById(id);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }

        return courseMapper.updateStatus(id, status) > 0;
    }

    /**
     * 增加浏览量
     */
    public boolean incrementViewCount(Long id) {
        return courseMapper.incrementViewCount(id) > 0;
    }

    /**
     * 获取待审核课程列表
     */
    public Map<String, Object> getPendingCourseList(Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<Course> courseList = courseMapper.selectPendingCourses(offset, pageSize);
        int total = courseMapper.countPendingCourses();

        Map<String, Object> result = new HashMap<>();
        result.put("list", courseList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 小程序端获取已发布课程列表
     */
    public Map<String, Object> getPublishedCourseList(String keyword, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<Course> courseList = courseMapper.selectPublishedCourses(keyword, offset, pageSize);
        int total = courseMapper.countPublishedCourses(keyword);

        Map<String, Object> result = new HashMap<>();
        result.put("list", courseList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 根据用户ID查询课程列表
     */
    public Map<String, Object> getCourseByPublisherId(Long publisherId, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<Course> courseList = courseMapper.selectByPublisherId(publisherId, offset, pageSize);
        int total = courseMapper.countByPublisherId(publisherId);

        Map<String, Object> result = new HashMap<>();
        result.put("list", courseList);
        result.put("total", total);
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalPages", (total + pageSize - 1) / pageSize);

        return result;
    }

    /**
     * 获取课程详情（包含浏览量增加）
     */
    public Course getCourseDetail(Long id, boolean incrementView) {
        Course course = courseMapper.selectById(id);
        if (course != null && incrementView) {
            courseMapper.incrementViewCount(id);
            course.setViewCount(course.getViewCount() + 1);
        }
        return course;
    }

    /**
     * 根据排序查询课程
     */
    public Map<String, Object> getCoursesBySortOrder(Integer sortOrder, Integer page, Integer pageSize) {
        int offset = (page - 1) * pageSize;
        List<Course> courseList = courseMapper.selectBySortOrder(sortOrder, offset, pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("list", courseList);
        result.put("page", page);
        result.put("pageSize", pageSize);

        return result;
    }

    /**
     * 更新课程排序
     */
    public boolean updateSortOrder(Long id, Integer sortOrder) {
        return courseMapper.updateSortOrder(id, sortOrder) > 0;
    }

    /**
     * 检查用户是否有权限操作该课程
     */
    public boolean checkCoursePermission(Long courseId, Long userId, Integer userType) {
        // 超级管理员可以操作所有课程
        if (userType == 2) {
            return true;
        }

        // 企业用户只能操作自己的课程
        Course course = courseMapper.selectById(courseId);
        return course != null && course.getPublisherId().equals(userId);
    }

    /**
     * 批量审核课程
     */
    public boolean batchAuditCourses(List<Long> courseIds, Integer status) {
        boolean allSuccess = true;
        for (Long courseId : courseIds) {
            if (!auditCourse(courseId, status)) {
                allSuccess = false;
            }
        }
        return allSuccess;
    }
}